/* eslint-disable*/
const readline = require("readline");

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.question("请输入当前项目的菜单key？", answer => {
  if (!answer) {
    console.error("请输入当前项目的菜单key");
    return;
  }
  readFile(answer);
  rl.close();
});

function readFile(docType) {
  let fs = require("fs");

  //index页面
  let indexText =
    `import ${docType} from "./${docType}.vue"
export default ${docType}
`;

  //默认面板
  let panelText =
    `<template>
<div>
  <div class="page-body" v-loading="loading">
    <data-view
      v-model="dataList"
      v-model:searchValue="searchValue"
      :header-btn="menuActionArray"
      :current-page="currentPage"
      :page-size="pageSize"
      :total="dataTotal"
      :delete-before="deleteBefore"
      @search="onSearch"
      @click-add="openModalView()"
      @delete-submit="onDeleteSubmit()"
      @update:current-page="onUpdateCurrentPage"
      @dblclick="openModalView"
    >
      <el-table-column type="selection" width="40" align="center" />
      <el-table-column type="index" width="50" label="#" />
      <el-table-column prop="Name" label="名称" />
      <el-table-column label="操作" width="120">
        <template #default="{ row }">
          <el-link type="primary"  @click="openModalView(row)" v-if="menuActionType.update">修改</el-link>
        </template>
      </el-table-column>
    </data-view>
  </div>

  <form-modal-view
    v-if="isShowFormModalView"
    ref="formModalViewRef"
    @submit="getData()"
    @close="isShowFormModalView = false"
  ></form-modal-view>
</div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
name: "${docType}",
})
</script>

<script lang="ts" setup>
import { ref, nextTick } from "vue";
import { ElMessageBox } from "element-plus";
import DataView from "@/components/DataView";
import { docType, ${docType}DataClass} from "@/model/${docType}";
import FormModalView from "./${docType}ModalView.vue";
import { queryGet } from "@/utils/api";
import { request } from "@/utils/axios";
import {appState} from "@/store/app"
import {getPanelUxBtn,getMenuAction} from "@/utils/bus";
let menuActionType=ref(getMenuAction("${docType}"))
let menuActionArray=ref(getPanelUxBtn("${docType}"))
let dataList = ref<${docType}DataClass[]>([]);

/**
 * 搜索内容
 */
let searchValue = ref("");

/**
 * 数据总数量
 */
let dataTotal = ref(0);

/**
 * 当前页数
 */
let currentPage = ref(1);

/**
 * 每页数据数量
 */
let pageSize = ref(25);

/**
 * 加载数据
 */
let loading = ref(false);

/**
 * 弹框是否展示
 */
let isShowFormModalView = ref(false)

/**
 * 弹框组件
 */
let formModalViewRef = ref();

/**
 * 当点击搜索的时候 
 */
function onSearch() {
currentPage.value = 1;
getData();
}

/**
 * 当前页面更新
 */
function onUpdateCurrentPage(count: number) {
currentPage.value = count;
//重新加载数据
getData();
}

/**
 * 删除之前
 */
function deleteBefore(selectList: ${docType}DataClass[]): Promise<void> {
return new Promise((resolve, reject) => {
  console.log(selectList);
  ElMessageBox.confirm("确定要进行删除操作吗", "提示", {
    type: "warning"
  })
    .then(() => {
      return Promise.all(selectList.map((item) => {
        return request("/"+ docType +"/Delete", {
          UnionGuid: item.UnionGuid,
          Id: item.Id
        }, {
          state: item.UnionGuid
        })
      }))
    })
    .then(() => {
      resolve();
    })
    .catch(reject)
})
}

/**
 * 当删除成功的时候
 */
function onDeleteSubmit() {
//重新获取数据
getData();
}

/**
 * 获取数据
 */
function getData() {
loading.value = true;
dataList.value = [];
queryGet({
  docType: docType,
  apiType: "PageList"
}, {
  Searchv: searchValue.value,
  Start: currentPage.value,
  Limit: pageSize.value
})
  .then((res) => {
    dataList.value = res.List.map((item: any) => {
      return new ${docType}DataClass(item);
    })
    dataTotal.value = res.Total;
  })
  .finally(() => {
    loading.value = false;
  })
}

/**
 * 打开弹框 
 */
function openModalView(row?: ${docType}DataClass) {
isShowFormModalView.value = true;
nextTick(() => {
  formModalViewRef.value.show(row);
})
}

/**
 * ====================
 *  页面初始化
 * ====================
 */
getData();
</script>

<style lang="less" scoped>
.page-body {
height: 100%;
width: 100%;
}
</style>`;
  //默认模态框
  let modalText =
    `<template>
  <div>
    <modal-view ref="modalViewRef" width="350px" :before-submit="beforeSubmit" @close="close">
      <el-form
        style="height: 190px;"
        ref="formRef"
        label-width="80px"
        :model="formData"
        :rules="rules"
        label-position="left"
        size="small"
      >
        <el-form-item label="编号">
          <el-input v-model="formData.Id" placeholder="自动生成" disabled></el-input>
        </el-form-item>
        <el-form-item label="名称" prop="Name">
          <el-input v-model="formData.Name"></el-input>
        </el-form-item>
      </el-form>
    </modal-view>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
  name: "${docType}ModalView",
})
</script>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import ModalView from "@/components/ModalView";
import { appAction } from "@/store/app";
import { docType, ${docType}DataClass} from "@/model/${docType}";
import { request } from "@/utils/axios";

let emit = defineEmits<{
  (e: "close"): void;
  (e: "submit"): void
}>()

/**
 * 弹框
 */
let modalViewRef = ref();

/**
 * 表单
 */
let formRef = ref();

/**
 * 表单
 */
let formData = ref<${docType}DataClass>(new ${docType}DataClass({}));


/**
 * 表单验证
 */
let rules = reactive({
  Name: [{ required: true, message: '当前项为必填项', trigger: 'blur' }],
})

/**
 * 页面展示
 */
function show(data?: any) {
  formData.value = new ${docType}DataClass(data || {});

  /**
   * 打开页面
   */
  modalViewRef.value.show();
}

/**
 *  保存前校验
 */
function beforeSubmit(): Promise<void> {
  return new Promise((resolve, reject) => {
    formRef.value.validate()
      .then(() => {

        let url = "";
        if (formData.value.Id) {
          //存在为修改
          url = "/"+docType +"/Update";
        } else {
          //不存在ID 为更新
          url = "/"+docType +"/Add";
        }

        //数据提交
        request(url, formData.value)
          .then(() => {
            ElMessage.success("表单数据保存成功");
            emit("submit");
            resolve();
          })
          .catch(() => {
            appAction.resetPageuuid();
            reject();
          })
      })
      .catch(reject)
  })
}

/**
 * 关闭页面
 */
function close() {
  emit("close")
}

/**
 * 导出
 */
defineExpose({
  show
})
/**
 * ====================
 *  页面初始化
 * ====================
 */


</script>

<style lang="less" scoped>
</style>`


  //默认配置页面
  let configText =
    `import { toPara } from "@/utils/base";

export const docType:string = "${docType}";

export class ${docType}DataClass {

  /**
   * 编号
   */
  Id: number | string = "";

  /**
   * 版本号
   */
  UnionGuid: string = "";

  /**
   * 名称
   */
  Name: string = "";

  constructor(para: any) {
    toPara(this, para)
  }
}`

  fs.mkdir(`./${docType}`, function (err) {
    if (!err) {
      fs.writeFile(`./${docType}/index.ts`, indexText, function (err) {
        if (err) {
          // console.log("index页面写入失败", err);
        } else {
          // console.log("index页面写入成功");
        }
      });

      fs.writeFile(`./${docType}/${docType}.vue`, panelText, function (err) {
        if (err) {
          // console.log("版面写入失败", err);
        } else {
          // console.log("版面写入成功");
        }
      });

      fs.writeFile(`./${docType}/${docType}ModalView.vue`, modalText, function (err) {
        if (err) {
          // console.log("模态框写入失败", err);
        } else {
          // console.log("模态框写入成功");
        }
      });

      fs.writeFile(`./${docType}/${docType}.ts`, configText, function (err) {
        if (err) {
          // console.log("配置文件写入失败", err);
        } else {
          // console.log("配置文件写入成功");
        }
      });
    }
  });
}